package com.csii.activiti.server.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.csii.activiti.server.abstraction.entity.ActCallbackMessage;
import com.csii.activiti.server.abstraction.entity.ActFlowCallbackResult;
import com.csii.activiti.server.abstraction.service.optional.ActCallbackService;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class ActCallbackServiceImpl implements ActCallbackService {

    private RestTemplate restTemplate = new RestTemplate();

    private final String okCode = "200";

    @Override
    public ActFlowCallbackResult callback(ActCallbackMessage callbackMessage, String callbackUrl) {
        ActFlowCallbackResult callbackResult = new ActFlowCallbackResult();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<ActCallbackMessage> entity = new HttpEntity<>(callbackMessage, headers);
        Map<String, Object> result = restTemplate.exchange(callbackUrl, HttpMethod.POST, entity, new ParameterizedTypeReference<Map<String, Object>>() {}).getBody();
        Object code = result.get("code");
        if (code != null && okCode.equals(code.toString())){
            callbackResult.setResult(true);
        }else{
            callbackResult.setResult(false);
            callbackResult.setMessage(JSONObject.toJSONString(result));
        }

        return callbackResult;
    }
}
